import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '../store'

// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/home.vue')
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import('../views/goods.vue')
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/order.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/user.vue'),
    redirect: '/user/cart',
    children: [
      { path: 'cart', component: () => import('../components/user/cart.vue'), }
    ]

  },
  {
    path: '/free',
    name: 'free',
    component: () => import('../views/free.vue')
  },
  {
    path: '/details',
    name: 'details',
    component: () => import('../views/details.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  if (to.path == "/user") {
    let token = localStorage.getItem("x-auth-token")
    if (token) {
      next()
    } else {
      store.dispatch('showToast/aysncShowToast', {
        isShow: true,
        msg: "请先登录",
        type: "danger"
      })

    }
  } else {
    next()
  }
})

export default router
